package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据toUserId查询Score最高的用户
    public RecommendUser queryWithMaxScore(Long toUserId) {
        //1.创建Criteria查询条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2.创建Query对象
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("score")))//倒序排序
                .limit(1);//每页查询一条，查询第一页
        //3.定义mongoTemplate查询（findOne）
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    //根据toUserId分页查询推荐用户
    public List<RecommendUser> queryRecommendUserList(Long toUserId, Integer page, Integer pagesize) {
        //1.创建Criteria查询条件
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2.创建Query对象
        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, RecommendUser.class);
        System.out.println("总数：" + count);
        //4.向Query对象中设置分页参数
        query.with(Sort.by(Sort.Order.desc("score")))//排序
                .skip((page-1)*pagesize)//指定查询的起始条数
                .limit(pagesize);//每页查询的条数
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //根据userId和toUserId查询推荐信息
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        Criteria criteria = Criteria.where("userId").is(userId).and("toUserId").is(toUserId);
        Query query = Query.query(criteria);

        return mongoTemplate.findOne(query,RecommendUser.class);
    }
}
